/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MainFrame.java
 *
 * Created on 2011-05-11, 07:09:12
 */
package jtmcraft.game;

import java.awt.event.KeyEvent;
import java.net.InetAddress;
import java.rmi.AlreadyBoundException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.logging.Level;
import java.util.logging.Logger;
import jtmcraft.game.communication.client.ClientInterface;
import jtmcraft.game.communication.server.JTMCraftServer;
import jtmcraft.game.communication.server.ServerInterface;
import jtmcraft.game.units.CollisionManager;
import jtmcraft.graphics.ImageResourceFactory;

/**
 *
 * @author tom
 */
public class JTMCraft extends javax.swing.JFrame {

    private JTMCraftServer jTMCraftServer;

    /** Creates new form MainFrame */
    public JTMCraft() {
        initComponents();
       // loadLabel.setVisible( false );
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        gamePanel = new jtmcraft.game.Game();
        gameMiniMap = new jtmcraft.game.GameMiniMap();
        gameButtonMenu = new jtmcraft.game.GameButtonMenu();
        playerName = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        serverIP = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        serverPort = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        runServerBtn = new javax.swing.JButton();
        joinBtn = new javax.swing.JButton();
        jLabel4 = new javax.swing.JLabel();
        messageEdit = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        playerPort = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        gamePanel.setBackground(new java.awt.Color(0, 0, 0));
        gamePanel.setPreferredSize(new java.awt.Dimension(640, 576));

        javax.swing.GroupLayout gamePanelLayout = new javax.swing.GroupLayout(gamePanel);
        gamePanel.setLayout(gamePanelLayout);
        gamePanelLayout.setHorizontalGroup(
            gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 640, Short.MAX_VALUE)
        );
        gamePanelLayout.setVerticalGroup(
            gamePanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 570, Short.MAX_VALUE)
        );

        gameMiniMap.setBackground(new java.awt.Color(0, 0, 0));
        gameMiniMap.setPreferredSize(new java.awt.Dimension(150, 150));

        javax.swing.GroupLayout gameMiniMapLayout = new javax.swing.GroupLayout(gameMiniMap);
        gameMiniMap.setLayout(gameMiniMapLayout);
        gameMiniMapLayout.setHorizontalGroup(
            gameMiniMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 171, Short.MAX_VALUE)
        );
        gameMiniMapLayout.setVerticalGroup(
            gameMiniMapLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 155, Short.MAX_VALUE)
        );

        gameButtonMenu.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)));

        javax.swing.GroupLayout gameButtonMenuLayout = new javax.swing.GroupLayout(gameButtonMenu);
        gameButtonMenu.setLayout(gameButtonMenuLayout);
        gameButtonMenuLayout.setHorizontalGroup(
            gameButtonMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 169, Short.MAX_VALUE)
        );
        gameButtonMenuLayout.setVerticalGroup(
            gameButtonMenuLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 298, Short.MAX_VALUE)
        );

        playerName.setText("TQ");

        jLabel1.setText("Name");

        serverIP.setText("127.0.0.1");

        jLabel2.setText("Serwer IP");

        serverPort.setText("2020");

        jLabel3.setText("Serwer Port");

        runServerBtn.setText("Postaw");
        runServerBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                runServerBtnActionPerformed(evt);
            }
        });

        joinBtn.setText("Dołącz");
        joinBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                joinBtnActionPerformed(evt);
            }
        });

        jLabel4.setText("Wiadomość:");

        messageEdit.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                messageEditKeyPressed(evt);
            }
        });

        jLabel5.setText("Player Port");

        playerPort.setText("2021");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(gamePanel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(messageEdit)))
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(gameMiniMap, javax.swing.GroupLayout.DEFAULT_SIZE, 171, Short.MAX_VALUE)
                    .addComponent(gameButtonMenu, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(runServerBtn)
                        .addGap(18, 18, 18)
                        .addComponent(joinBtn))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)
                                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 61, Short.MAX_VALUE)
                                    .addComponent(jLabel3))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel5)
                                .addGap(8, 8, 8)))
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(playerPort, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                            .addComponent(playerName, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                            .addComponent(serverPort, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE)
                            .addComponent(serverIP, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE))))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                    .addComponent(gamePanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 570, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(gameMiniMap, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(gameButtonMenu, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(runServerBtn)
                            .addComponent(joinBtn))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(playerName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(8, 8, 8)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(serverIP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel2))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(serverPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel4)
                        .addComponent(messageEdit, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(playerPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel5)))
                .addContainerGap(23, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void createClient( String playerName, int port ) throws RemoteException, Exception 
    {
        
        ClientInterface stub = (ClientInterface) UnicastRemoteObject.exportObject( gamePanel, 0);
        
        try {
            LocateRegistry.createRegistry(port);
            Registry registry = LocateRegistry.getRegistry(port);
            registry.bind(playerName, stub);
        } catch (Exception ex) {
            UnicastRemoteObject.unexportObject(gamePanel, true);
            Logger.getLogger(JTMCraft.class.getName()).log(Level.SEVERE, null, ex);
            throw new Exception( ex.getMessage() );
        } 
    }
    
    private void destroyClient( String playerName, int port, ClientInterface stub  ) throws RemoteException, AlreadyBoundException, NotBoundException
    {
        if( stub != null )
        {
            UnicastRemoteObject.unexportObject(stub, true);
        }
        LocateRegistry.createRegistry(port);
        Registry registry = LocateRegistry.getRegistry(port);        
        registry.unbind(playerName);
    }
        
    private void joinBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_joinBtnActionPerformed

        String errorMsg = "";

        //tworzymy klienta
        try {
            createClient(getPlayerName(), Integer.parseInt(getPlayerPort()));
        } catch (Exception ex) {
            Logger.getLogger(JTMCraft.class.getName()).log(Level.SEVERE, null, ex);
            errorMsg = "Błąd: " + ex.getMessage().split("\n")[0];
        }

        if (!errorMsg.isEmpty()) return;


        //laczymy sie z serwerem
        ServerInterface stub = null;
        int playerId = 0;
        try {
            Registry registry = LocateRegistry.getRegistry(getHost(), Integer.parseInt(getServerPort()));
            stub = (ServerInterface) registry.lookup(JTMCraftServer.name);
            playerId = stub.join(getPlayerName(), InetAddress.getLocalHost().getHostAddress(), Integer.parseInt(getPlayerPort()));
        } catch (Exception ex) {
            Logger.getLogger(JTMCraft.class.getName()).log(Level.SEVERE, null, ex);
            errorMsg = "Błąd: " + ex.getMessage().split("\n")[0];
        }

        //jezeli blad
        if (!errorMsg.isEmpty()) {
            try {
                destroyClient(getPlayerName(), Integer.parseInt(getPlayerPort()), gamePanel);
            } catch (Exception ex) {
                Logger.getLogger(JTMCraft.class.getName()).log(Level.SEVERE, null, ex);
                errorMsg = "Błąd: " + ex.getMessage().split("\n")[0];
            }
            
            return;
        }
        
        runServerBtn.setEnabled(false);
        joinBtn.setEnabled(false);  
        
        LoadImage();
        startGame(stub, playerId);

    }//GEN-LAST:event_joinBtnActionPerformed

    private void runServerBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_runServerBtnActionPerformed
        String errorMsg = "";
        try {
            startServer( Integer.parseInt( getServerPort()) );
        } catch (Exception ex) {
            Logger.getLogger(JTMCraft.class.getName()).log(Level.SEVERE, null, ex);
            errorMsg = "Błąd: " + ex.getMessage().split("\n")[0];
        }

        if( !errorMsg.isEmpty() ) return;
        
        try {
            createClient(getPlayerName(), Integer.parseInt( getPlayerPort() ));
        } catch (Exception ex) {
            Logger.getLogger(JTMCraft.class.getName()).log(Level.SEVERE, null, ex);
            errorMsg = "Błąd: " + ex.getMessage().split("\n")[0];
        } 
        
        if( !errorMsg.isEmpty() ) return;
        
        int playerId = 0;
        try {
            playerId = jTMCraftServer.join(getPlayerName(), InetAddress.getLocalHost().getHostAddress(), Integer.parseInt( getPlayerPort() ) );
        } catch (Exception ex) {
            Logger.getLogger(JTMCraft.class.getName()).log(Level.SEVERE, null, ex);
            errorMsg = "Błąd: " + ex.getMessage().split("\n")[0];
        }
        
        //jezeli blad
        if (!errorMsg.isEmpty()) {
            try {
                destroyClient(getPlayerName(), Integer.parseInt(getPlayerPort()), gamePanel);
            } catch (Exception ex) {
                Logger.getLogger(JTMCraft.class.getName()).log(Level.SEVERE, null, ex);
                errorMsg = "Błąd: " + ex.getMessage().split("\n")[0];
            }
            
            return;
        }
        
       runServerBtn.setEnabled(false);
       joinBtn.setEnabled(false);
       LoadImage();
       startGame(jTMCraftServer, playerId);
    }//GEN-LAST:event_runServerBtnActionPerformed

    private void LoadImage()
    {        
        ImageResourceFactory.getInstance().loadImages();    
    }
    
    private void messageEditKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_messageEditKeyPressed
        if( evt.getKeyCode() == KeyEvent.VK_ENTER)
        {
            gamePanel.sendMessage( messageEdit.getText());
            messageEdit.setText("");
            gamePanel.requestFocus();
        }
    }//GEN-LAST:event_messageEditKeyPressed

    private void startGame(ServerInterface serverInterface, int playerId) {
        gamePanel.repaint();
        gamePanel.InitGame(gameMiniMap, gameButtonMenu, playerId, serverInterface);
        joinBtn.setEnabled(false);
        new Thread(gamePanel).start();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        CollisionManager cm = CollisionManager.getInstance();
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                JTMCraft jtmc = new JTMCraft();
                jtmc.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private jtmcraft.game.GameButtonMenu gameButtonMenu;
    private jtmcraft.game.GameMiniMap gameMiniMap;
    public jtmcraft.game.Game gamePanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JButton joinBtn;
    private javax.swing.JTextField messageEdit;
    private javax.swing.JTextField playerName;
    private javax.swing.JTextField playerPort;
    private javax.swing.JButton runServerBtn;
    private javax.swing.JTextField serverIP;
    private javax.swing.JTextField serverPort;
    // End of variables declaration//GEN-END:variables

    public String getPlayerName() {
        return playerName.getText();
    }

    public String getHost() {
        return serverIP.getText();
    }

    public String getServerPort() {
        return serverPort.getText();
    }
    
    public String getPlayerPort()
    {
        return playerPort.getText();
    }

    public void startServer(int port) throws Exception{
        
        if (jTMCraftServer != null) {
            return;
        }

        jTMCraftServer = new JTMCraftServer(port);

        ServerInterface stub; 
        try {
            stub = (ServerInterface) UnicastRemoteObject.exportObject(jTMCraftServer, 0);
        } catch (RemoteException ex) {
            Logger.getLogger(JTMCraft.class.getName()).log(Level.SEVERE, null, ex);
            throw new Exception( ex.getMessage() );
        }
       
        try {
            LocateRegistry.createRegistry(port);
            Registry registry = LocateRegistry.getRegistry(port);
            registry.bind(JTMCraftServer.name, stub);
        } catch (Exception ex) {
            Logger.getLogger(JTMCraft.class.getName()).log(Level.SEVERE, null, ex);
            UnicastRemoteObject.unexportObject(stub, true);
            throw new Exception(ex.getMessage());
        }
        

    }
}
